<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>科泰教育 - 实时温度监控</title>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="http://code.highcharts.com/highcharts.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f8f9fa;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            background-color: #2c3e50;
            color: white;
            padding: 20px;
            text-align: center;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .header h1 {
            margin: 0;
            font-size: 1.8rem;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .header h1 i {
            margin-right: 10px;
        }

        .chart-wrapper {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            padding: 20px;
            margin-bottom: 20px;
        }

        #container {
            width: 100%;
            height: 350px;
        }

        .controls {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 10px;
            margin-bottom: 20px;
        }

        .btn {
            padding: 10px 15px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
            display: flex;
            align-items: center;
        }

        .btn:hover {
            background-color: #2980b9;
        }

        .btn i {
            margin-right: 5px;
        }

        .status {
            text-align: center;
            margin-top: 10px;
            font-size: 0.9rem;
        }

        .status.error {
            color: #e74c3c;
        }

        .status.success {
            color: #2ecc71;
        }

        .info-panel {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .info-card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            padding: 15px;
            text-align: center;
        }

        .info-card h3 {
            margin: 0 0 10px 0;
            font-size: 1rem;
            color: #7f8c8d;
        }

        .info-value {
            font-size: 1.5rem;
            font-weight: bold;
        }

        .temp-normal {
            color: #3498db;
        }

        .temp-warning {
            color: #f39c12;
        }

        .temp-danger {
            color: #e74c3c;
        }

        .last-update {
            font-size: 0.8rem;
            color: #7f8c8d;
            margin-top: 5px;
        }

        @media (max-width: 768px) {
            .header h1 {
                font-size: 1.5rem;
            }

            #container {
                height: 350px;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1><i class="fa fa-thermometer-half"></i>实时温度监控系统</h1>
    </div>

    <div class="info-panel">
        <div class="info-card">
            <h3>当前温度</h3>
            <div class="info-value temp-normal" id="current-temp">--</div>
        </div>
        <div class="info-card">
            <h3>最高温度</h3>
            <div class="info-value" id="max-temp">--</div>
        </div>
        <div class="info-card">
            <h3>最低温度</h3>
            <div class="info-value" id="min-temp">--</div>
        </div>
        <div class="info-card">
            <h3>更新时间</h3>
            <div class="info-value" id="update-time">--</div>
        </div>
    </div>

    <div class="chart-wrapper">
        <div class="controls">
            <button class="btn" id="refresh-btn">
                <i class="fa fa-refresh"></i>立即刷新
            </button>
            <button class="btn" id="fullscreen-btn">
                <i class="fa fa-expand"></i>全屏查看
            </button>
            <button class="btn" id="export-btn">
                <i class="fa fa-download"></i>导出数据
            </button>
        </div>

        <div id="container"></div>

        <div class="status" id="status-message"></div>
    </div>
</div>

<script>
    $(document).ready(function() {
        // 初始化图表
        var chart = Highcharts.chart('container', {
            chart: {
                type: 'spline',
                backgroundColor: '#f9fafc',
                borderWidth: 0,
                borderRadius: 8,
                style: {
                    fontFamily: "'Segoe UI', sans-serif"
                },
                events: {
                    load: function() {
                        var series = this.series[0];
                        var updateInterval = setInterval(function() {
                            $.ajax({
                                url: '/getCurrentLot?size=1',
                                type: 'GET',
                                dataType: 'json',
                                success: function(rntData) {
                                    if (!rntData || rntData.length === 0) {
                                        showStatus('未获取到新数据', 'error');
                                        return;
                                    }

                                    try {
                                        var point = rntData[0];
                                        var x = new Date(point.collectTimes).getTime();
                                        var y = parseFloat(point.temperature);

                                        if (isNaN(x) || isNaN(y)) {
                                            showStatus('数据格式错误', 'error');
                                            return;
                                        }

                                        series.addPoint([x, y], true, true);
                                        showStatus('数据更新成功');

                                        // 更新标题和副标题
                                        chart.setTitle({
                                            text: `实时温度监控 - 当前: ${y.toFixed(1)}°C`
                                        });

                                        chart.setTitle(null, {
                                            text: `更新时间: ${Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', x)}`
                                        });

                                        // 更新信息面板
                                        $('#current-temp').text(`${y.toFixed(1)}°C`);
                                        $('#update-time').text(Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', x));

                                        // 设置温度颜色
                                        var tempClass = 'temp-normal';
                                        if (y > 30) tempClass = 'temp-danger';
                                        else if (y > 25) tempClass = 'temp-warning';
                                        $('#current-temp').attr('class', `info-value ${tempClass}`);

                                        // 计算最高/最低温度
                                        var points = series.data;
                                        var temps = points.map(p => p.y);
                                        $('#max-temp').text(`${Math.max(...temps).toFixed(1)}°C`);
                                        $('#min-temp').text(`${Math.min(...temps).toFixed(1)}°C`);
                                    } catch (e) {
                                        showStatus('处理数据时出错: ' + e.message, 'error');
                                    }
                                },
                                error: function(jqXHR, textStatus, errorThrown) {
                                    showStatus('获取数据失败: ' + textStatus, 'error');
                                }
                            });
                        }, 2000);

                        // 按钮事件
                        $('#refresh-btn').click(function() {
                            showStatus('正在刷新数据...');
                            // 触发数据更新
                            $.ajax({
                                url: '/getCurrentLot?size=1',
                                success: function(rntData) {
                                    if (rntData && rntData.length > 0) {
                                        var point = rntData[0];
                                        var x = new Date(point.collectTimes).getTime();
                                        var y = parseFloat(point.temperature);
                                        series.addPoint([x, y], true, true);
                                        showStatus('数据已刷新');
                                    }
                                }
                            });
                        });

                        $('#fullscreen-btn').click(function() {
                            var element = document.getElementById('container');
                            if (element.requestFullscreen) {
                                element.requestFullscreen();
                            } else if (element.webkitRequestFullscreen) {
                                element.webkitRequestFullscreen();
                            } else if (element.msRequestFullscreen) {
                                element.msRequestFullscreen();
                            }
                        });

                        $('#export-btn').click(function() {
                            chart.exportChartLocal();
                        });
                    }
                }
            },
            title: {
                text: '实时温度监控',
                style: {
                    fontSize: '20px',
                    color: '#2c3e50',
                    fontWeight: 'bold'
                }
            },
            subtitle: {
                text: '等待数据更新...',
                style: {
                    color: '#7f8c8d'
                }
            },
            xAxis: {
                type: 'datetime',
                timezone: 'Asia/Shanghai',
                gridLineWidth: 1,
                gridLineColor: '#f0f0f0',
                labels: {
                    style: {
                        fontSize: '11px'
                    }
                }
            },
            yAxis: {
                title: {
                    text: '温度 (°C)'
                },
                tickInterval: 2,
                min: 10,
                max: 40,
                gridLineWidth: 1,
                gridLineColor: '#f0f0f0'
            },
            tooltip: {
                backgroundColor: 'rgba(255, 255, 255, 0.95)',
                borderColor: '#ddd',
                borderRadius: 6,
                shadow: true,
                style: {
                    fontSize: '13px'
                },
                formatter: function() {
                    return `<b>${this.series.name}</b><br/>
                                ${Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x)}<br/>
                                <span style="font-size:1.2em">${this.y.toFixed(1)}°C</span>`;
                }
            },
            plotOptions: {
                spline: {
                    lineWidth: 3,
                    marker: {
                        enabled: false,
                        radius: 3,
                        states: {
                            hover: {
                                enabled: true,
                                radius: 5
                            }
                        }
                    },
                    states: {
                        hover: {
                            lineWidth: 4
                        }
                    }
                }
            },
            legend: {
                enabled: false
            },
            exporting: {
                enabled: true,
                buttons: {
                    contextButton: {
                        text: '导出图表',
                        menuItems: ['downloadPNG', 'downloadJPEG', 'downloadCSV']
                    }
                }
            },
            series: [{
                name: '温度',
                color: '#3498db',
                data: (function() {
                    var data = [];
                    $.ajax({
                        url: '/getCurrentLot?size=20',
                        type: 'GET',
                        dataType: 'json',
                        async: false,
                        success: function(obj) {
                            if (obj && obj.length > 0) {
                                obj.forEach(function(d) {
                                    data.push([
                                        Date.parse(d.collectTimes),
                                        parseFloat(d.temperature)
                                    ]);
                                });
                                showStatus(`已加载 ${data.length} 条历史数据`);
                            } else {
                                showStatus('无历史数据', 'error');
                            }
                        },
                        error: function() {
                            showStatus('获取历史数据失败', 'error');
                            // 添加默认数据
                            var time = new Date().getTime();
                            for (var i = -19; i <= 0; i += 1) {
                                data.push([time + i * 1000, 25 + Math.random() * 5]);
                            }
                        }
                    });
                    return data.reverse();
                })()
            }]
        });

        // 显示状态消息
        function showStatus(message, type = 'info') {
            var statusEl = $('#status-message');
            statusEl.text(message);

            if (type === 'error') {
                statusEl.addClass('error').removeClass('success');
            } else {
                statusEl.removeClass('error').addClass('success');
            }

            // 3秒后自动清除
            setTimeout(function() {
                statusEl.fadeOut(500, function() {
                    $(this).text('').show().removeClass('error success');
                });
            }, 3000);
        }
    });
</script>
</body>
</html>